﻿

using DualPlaneFR4Paster.Common.Services;
using DualPlaneFR4Paster.Extensions;
using Prism.Ioc;
using Prism.Services.Dialogs;
using System;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;

namespace DualPlaneFR4Paster.ViewModels.Dialogs
{
    public class AlarmDialogViewModel : DialogViewModel
    {
        private IPLCModbusService plcModbus;
        private CancellationTokenSource source;
        private string alarmContent;
        public string AlarmContent
        {
            get { return alarmContent; }
            set { SetProperty(ref alarmContent, value); }
        }
        public override void OnDialogClosed()
        {
            plcModbus.SetM(1, 2000, false);
            if (source != null)
            {
                source.Cancel();
            }
        }

        public override void OnDialogOpened(IDialogParameters parameters)
        {
            plcModbus.SetM(1, 2000, true);
            AlarmContent = parameters.GetValue<string>("ContainStr");
            source = new CancellationTokenSource();
            CancellationToken token = source.Token;
            Task.Run(() => Run(token), token);
        }
        public AlarmDialogViewModel(IContainerProvider containerProvider) : base(containerProvider)
        {
            Title = "报警窗口";
            plcModbus = containerProvider.Resolve<IPLCModbusService>("PLCModbus");
            aggregator.ResgiterMessage(arg =>
            {
                plcModbus.SetM(1, 2000, true);
                AlarmContent = arg.Message;
            }, "UpdateAlarm");
        }
        private void Run(CancellationToken token)
        {
            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }
                try
                {
                    if (plcModbus.XCoils_X0[1])
                    {
                        System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
                        {
                            OnRequestClose(new DialogResult(ButtonResult.No));
                        }));
                    } 
                }
                catch { }
                System.Threading.Thread.Sleep(100);
            }
        }
    }
}
